package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.Dialog.BaseDialogView;
import com.epfresh.api.widget.MultipleStatusView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.JoinPrepareListViewBinder;
import com.epfresh.supplier.dialog.FilterCategoryDialog;
import com.epfresh.supplier.dialog.FilterJoinDialog;
import com.epfresh.supplier.entity.JoinPrepare;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.widget.WrapContentLinearLayoutManager;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;
/*联营备货*/
public class JoinPrepareListActivity extends BaseActivity implements FilterJoinDialog.SelectCondition{

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    JoinPrepareListViewBinder itemViewBinder;
    LinearLayoutManager layoutManagerGoods;
    private MultipleStatusView msvGoods;

    RecyclerView rv;


    int pageNum = 0;
    private View llTitle,ll_state,ll_store;
    private TextView tv_state,tv_store;
    private ImageView iv_store,iv_state;
    private int ivSelectFlag;//0,1,2 未出现dialog；city；category

    private int mSuspensionPosition = 1;

    private int dialogHeight =   LocalDisplay.dp2px(84);

/*

    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqSupplyStoreDyn(pageNum + 1);
        }
    };
*/

    @Override
    public void selectCity(String condition,String name) {
        if(dialogPosition == 0) {
            stockStatus = condition;
            cityName = name;
            reqSupplyStoreDyn(0);
            commonDismiss(stateFilterJoinDialog);
        }else{
            merchantId = condition;
            merchantName = name;
            reqSupplyStoreDyn(0);
            commonDismiss(storeFilterJoinDialog);
        }
    }

    @Override
    public void selectCategory(String condition,String name) {}

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            freshFlag = true;
            reqSupplyStoreDyn(0);
            //reqFilter();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    int dialogPosition;
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_state:
                commonDismiss(stateFilterJoinDialog);
                openCityDialog(0);
                break;
            case R.id.ll_store:
                commonDismiss(storeFilterJoinDialog);
                openCityDialog(1);
                break;
        }

    }

    FilterJoinDialog stateFilterJoinDialog;
    FilterJoinDialog storeFilterJoinDialog;
    private void openCityDialog(int position) {
        if(buyerFilter==null){
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }if(position == 0) {
            if (stateFilterJoinDialog == null) {
                stateFilterJoinDialog = new FilterJoinDialog(this, "待备货");
                stateFilterJoinDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                    @Override
                    public void onDismiss(Object o) {
                        tv_state.setText(cityName);
                        iv_state.setImageResource(R.mipmap.select_down);
                    }
                });
                stateFilterJoinDialog.setSelectCondition(this);
                iv_state.setImageResource(R.mipmap.select_up);
                dialogPosition = position;
                stateFilterJoinDialog.show(buyerFilter.getStockStatuss(), dialogHeight);
            } else {
                if (stateFilterJoinDialog.isShowing()) {
                    stateFilterJoinDialog.dismiss();
                } else {
                    iv_state.setImageResource(R.mipmap.select_up);
                    dialogPosition = position;
                    stateFilterJoinDialog.show(buyerFilter.getStockStatuss(), dialogHeight);
                }
            }
        }else{
            if (storeFilterJoinDialog == null) {
                storeFilterJoinDialog = new FilterJoinDialog(this, "全部收货方");
                storeFilterJoinDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                    @Override
                    public void onDismiss(Object o) {
                        tv_store.setText(merchantName);
                        iv_store.setImageResource(R.mipmap.select_down);
                    }
                });
                storeFilterJoinDialog.setSelectCondition(this);
                iv_store.setImageResource(R.mipmap.select_up);
                dialogPosition = position;
                storeFilterJoinDialog.show(buyerFilter.getMerchantIds(), dialogHeight);
            } else {
                if (storeFilterJoinDialog.isShowing()) {
                    storeFilterJoinDialog.dismiss();
                } else {
                    iv_store.setImageResource(R.mipmap.select_up);
                    dialogPosition = position;
                    storeFilterJoinDialog.show(buyerFilter.getMerchantIds(), dialogHeight);
                }
            }
        }
    }

    public void commonDismiss(FilterJoinDialog dialog){
        if(dialog !=null)
            dialog.dismiss();
        if(stateFilterJoinDialog != null)
            stateFilterJoinDialog.dismiss();
        if(storeFilterJoinDialog != null)
            storeFilterJoinDialog.dismiss();
    }

    String stockStatus = "1",cityName = "待备货";
    String merchantId = "",merchantName = "全部收货方";
    public void reqSupplyStoreDyn(int pageNum) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_order_supplier_order_stock_list);
        RequestEntityMapSupply.putParameter("stockStatus", stockStatus);
        RequestEntityMapSupply.putParameter("merchantId", merchantId);
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("pageSize", 10);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_order_supplier_order_stock_list, onSupplyStoreDynRequestListener);
    }
    boolean freshFlag;

    private OnRequestListener<ContentEntity<JoinPrepare>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<JoinPrepare>>() {
        @Override
        public ContentEntity<JoinPrepare> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, JoinPrepare.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            msvGoods.showNoNetwork();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            msvGoods.showError();
        }

        @Override
        public void onStart(Object tag) {
            if(!freshFlag) {
                showProgressDialog();
                freshFlag = false;
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<JoinPrepare>> response, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            ContentEntity<JoinPrepare> responseElement = response.getResponseElement();
            boolean last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<JoinPrepare> content = responseElement.getContent();
            //第一页
            if (number == 0) {
                mItems.clear();
            }
            pageNum = number;
            if (content != null) {
                for(int i=0;i<content.size();i++){
                    content.get(i).getSupplyProductList().get(0).setHeader(true);
                    content.get(i).getSupplyProductList().get(0).setDateStr(content.get(i).getDateStr());
                    mItems.addAll(content.get(i).getSupplyProductList());
                }
                if (mItems.size() == 0) {
                    //loadMoreDelegate.setStatusEmpty();
                    msvGoods.showEmpty();
                }else {
                    msvGoods.showContent();
                    //loadMoreDelegate.addLoadItemOnly(mItems);
                    //最后一个
                    if (last) {
                        //loadMoreDelegate.setStatusNoMore();
                    } else {
                        //loadMoreDelegate.setStatusNormal();
                    }
                }
                mMultiAdapter.notifyDataSetChanged();
            }
        }
    };

    BuyerFilter buyerFilter;

    private void reqFilter() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_order_supplier_order_stock_list_query);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_order_supplier_order_stock_list_query, onSupplyFilterRequestListener);
    }

    private OnRequestListener<BuyerFilter> onSupplyFilterRequestListener = new OnRequestListener<BuyerFilter>() {
        @Override
        public BuyerFilter jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BuyerFilter.class);
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<BuyerFilter> response, Object tag) {
            buyerFilter = response.getResponseElement();
            BuyerFilter.CitiesBean bean = new BuyerFilter.CitiesBean();
            bean.setCode("");
            bean.setSelectFlag(true);
            bean.setName("全部收货方");
            buyerFilter.getMerchantIds().add(0,bean);
            buyerFilter.getStockStatuss().get(0).setSelectFlag(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_prepare_list);
        setToolbarTitle("备货");
        initView();
    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_make_agent_back);
        initHeadView();
        rv = (RecyclerView) findViewById(R.id.rv_goods);
        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);
        msvGoods.setHint("无备货记录");
        msvGoods.setIcon(R.mipmap.nostandingbook);

        ll_store = findViewById(R.id.ll_store);
        ll_state = findViewById(R.id.ll_state);
        ll_state.setOnClickListener(this);
        ll_store.setOnClickListener(this);
        tv_state = (TextView)findViewById(R.id.tv_state);
        tv_store = (TextView)findViewById(R.id.tv_store);
        iv_store = (ImageView) findViewById(R.id.iv_store);
        iv_state = (ImageView)findViewById(R.id.iv_state);
        layoutManagerGoods = new WrapContentLinearLayoutManager(this);
        layoutManagerGoods.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(layoutManagerGoods);
        mMultiAdapter = new MultiTypeAdapter();
        //LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        //loadMoreDelegate.attach(rv, loadMoreSubject);
        itemViewBinder = new JoinPrepareListViewBinder();
        itemViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
/*                if(data instanceof JoinPrepare.ProductsBean && mBaseStores!=null){
                    for(int i=0;i<mBaseStores.size();i++){
                        if(mBaseStores.get(i).getProducts().contains(data)){
                            intoProductDetail(mBaseStores.get(i).getId(),((JoinPrepare.ProductsBean)data).getId());
                            return;
                        }
                    }
                }*/
            }
        });
        //mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        mMultiAdapter.register(JoinPrepare.SupplyProductListBean.class,itemViewBinder);
        rv.setAdapter(mMultiAdapter);
        mMultiAdapter.setItems(mItems);
        reqSupplyStoreDyn(pageNum);
        reqFilter();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //记录当前fragment的下标
        /*outState.putInt(Constant.KEY_HOME_STATE_INDEX, currentFragmentIndex);
        outState.putInt("orderType", orderType);*/
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x65 && resultCode == RESULT_OK) {
        }
    }
}
